/*
 * ! ******************************************************************************
 *
 * Pentaho Data Integration
 *
 * Copyright (C) 2021 by YuZhou Big Data Laboratory : http://www.yzbdl.ac.cn
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 ******************************************************************************/
package org.pentaho.di.ui.core.dialog;

import java.lang.reflect.Method;

import org.yzbdl.lanius.ui.spoon.market.browser.function.MarketFunction;

/**
 * Displays an HTML page.
 *
 * @author Matt
 * @since 22-12-2005
 */
public class WelcomeBrowserCallJava extends MarketFunction {

    @Override
    protected String getJsFuntionName() {
        return "welcomeCallJava";
    }

    @Override
    protected Object javaFunction(Object[] arg0) {
        try {
            openBrowser((String)arg0[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void openBrowser(String url) throws Exception {
        String osName = System.getProperty("os.name", "");// 获取操作系统的名字
        if (osName.startsWith("Windows")) {// windows
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else if (osName.startsWith("Mac OS")) {// Mac
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", String.class);
            openURL.invoke(null, url);
        } else {// Unix or Linux
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++) { // 执行代码，在brower有值后跳出，
                // 这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0) {
                    browser = browsers[count];
                }
            }
            if (browser == null) {
                throw new RuntimeException("未找到任何可用的浏览器");
            } else {// 这个值在上面已经成功的得到了一个进程。
                Runtime.getRuntime().exec(new String[] {browser, url});
            }
        }
    }

}